package org.dong.Controller;

import com.alibaba.fastjson.JSON;
import org.dong.Dao.FileDaoImpl;
import org.dong.Dao.TranDaoImpl;
import org.dong.Pojo.Dto;
import org.dong.Pojo.HttpRequest;
import org.dong.Pojo.HttpResponse;
import org.dong.Tool.Data;

import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class UploadController implements ServerLet {

    @Override
    public void server(HttpRequest request, OutputStream os) {
        Dto dto = new Dto();
        String msg = "ok";
        //查找数据中是否存在此记录

        String[] list = request.getRequestData().split("&");
        //获取文件ID
        String file_name = URLDecoder.decode((list[0].split("=")[1]));
        BigDecimal file_size = new BigDecimal(list[1].split("=")[1]);
        String file_src = URLDecoder.decode((list[2].split("=")[1]));

        Map<String,String> map = new HashMap<>();
        map.put("file_name",file_name);
        map.put("file_size",file_size+"");
        map.put("file_src",file_src);
        map.put("id",Data.user.getId()+"");

        //上传文件
        if(new FileDaoImpl().upload(map)){
            //查找最新上传的文件ID
            int id = new FileDaoImpl().selFileId(map);
            if(id != 0){
                //增加记录
                Map<String,String> log = new HashMap<>();
                log.put("file_id",id+"");
                log.put("type","0");
                if(new TranDaoImpl().addDownload(log)){
                    dto.setErrMsg("上传成功");
                    dto.setStatusCode(2000);
                }else{
                    dto.setStatusCode(2001);
                    dto.setErrMsg("增加上传记录失败");
                }
            }else{
                dto.setStatusCode(2001);
                dto.setErrMsg("上传失败");
            }
        }else{
            dto.setStatusCode(2001);
            dto.setErrMsg("上传失败");
        }



        msg = JSON.toJSONString(dto);

        new HttpResponse(os,request.getUrl(),msg);

    }
}
